package com.thd.framework.db.intereptor;


import com.thd.framework.basic.obligate.CurrentUserUtil;
import com.thd.framework.basic.utils.SpringUtils;
import com.thd.framework.basic.utils.StringUtils;
import com.thd.framework.db.entity.BasicEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;

/**
 * mybatis拦截器，自动注入创建人、创建时间、修改人、修改时间
 * @Author scott
 * @Date  2019-01-19
 *
 */
@Slf4j
@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class MybatisInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		String sqlId = mappedStatement.getId();
		log.debug("------sqlId------" + sqlId);
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		Object parameter = invocation.getArgs()[1];
		log.debug("------sqlCommandType------" + sqlCommandType);


		boolean dealDefaultColumn = false;
		if (parameter != null) {
			dealDefaultColumn = true;
		}

		// 如果实体是BasicEntity的子类
		if(dealDefaultColumn && parameter instanceof BasicEntity){
			dealDefaultColumn = true;
		}

		BasicEntity entity = null;
		try{
			entity = (BasicEntity)parameter;
		}catch (Exception e){
			log.error("fill default column error :" + e.getMessage());
			dealDefaultColumn = false;
		}


		// 是否在IOC容器中有实现了CurrentUserUtil接口的类

		CurrentUserUtil currentUserUtil = null;
		try{
			currentUserUtil = SpringUtils.getBean(CurrentUserUtil.class);
		}catch(Exception e){
			dealDefaultColumn = false;
		}
		if(null == currentUserUtil){
			dealDefaultColumn = false;
		}

		if(!dealDefaultColumn){
			return invocation.proceed();
		}

		Date d = new Date();
		if (SqlCommandType.INSERT == sqlCommandType) {
			if(null == entity.getCreateTime()) {
				entity.setCreateTime(d);
			}
			if(StringUtils.isEmpty(entity.getCreateBy())) {
				entity.setCreateBy(currentUserUtil.getCurrentUserId());
			}
//			if(MyStringUtils.isEmpty(entity.getTenantId())){
//				entity.setTenantId(currentUserUtil.getTenantId());
//			}
		}
		if (SqlCommandType.UPDATE == sqlCommandType) {
			entity.setModifyTime(d);
			entity.setModifyBy(currentUserUtil.getCurrentUserId());
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
	}


}
